import { memo, useMemo, useRef, useState } from "react";
import BuyBtnStyle from "./style";
import { CloseOutline, PhoneFill } from "antd-mobile-icons";
import { PRICE_ICON } from "../../constant";
import { useNavigate } from "react-router-dom";
import { ProductType } from "../../types/product";
import { routeItmeType } from "../../router";
import classNames from "classnames";
import { useFetch_getProductInfo } from "../../service/product";
import { Modal, Toast } from "antd-mobile";
import { useFetchCreateOrder, useFetchGetOrdersByProduct } from "../../service/order";
import { craeteOrderCode } from "../../utils";

const BuyBtn = memo(
  (props: {
    data: ProductType;
    isPayment: boolean;
    buy_num?: number;
    orgId?: string;
    bindTel?: boolean;
  }) => {
    const { data, isPayment, buy_num = 1, orgId, bindTel = true } = props;
    const [newProductData, setNewProductData] = useState<ProductType>(data);
    const { refetch } = useFetch_getProductInfo(data?.id);
    const { createOrder, loading: craeteLoading } = useFetchCreateOrder();
    const { data: OrderData, loading: getOrderLoading } =
      useFetchGetOrdersByProduct(newProductData?.id);
    const nav = useNavigate();
    const orderCode = useRef<string>(craeteOrderCode());

    const buyNumByOrder = useMemo(() => {
      let num = 0;
      if (OrderData) {
        OrderData.forEach((item) => {
          num += item.buyNum;
        });
      }
      return num;
    }, [OrderData]);
    const canSell = useMemo(() => {
      return newProductData.stock - newProductData.sellNum === 0;
    }, [newProductData]);

    const buyBtnClick = async () => {
      // 提交支付订单
      if (isPayment) {
        const res = await refetch({ id: newProductData.id });
        const newProduct = res.data.getProductInfo.data as ProductType;
        setNewProductData(newProduct);
        const curStock = newProduct.stock - newProduct.sellNum;

        // 售完
        if (curStock === 0) {
          Toast.show({
            icon: <CloseOutline />,
            content: `该商品已售完！ 即将跳转到首页`
          });
          setTimeout(() => {
            nav(`/${routeItmeType.HOME}`);
          }, 1500);
          return;
        } else {
          if (curStock < buy_num) {
            void Modal.alert({
              content: "所选数量大于库存，已为您自动调整"
            });
          }
          Toast.show({
            icon: "loading",
            content: `创建订单中`
          });
          void createOrder({
            productId: newProduct.id,
            buyNum: curStock < buy_num ? curStock : buy_num,
            buyPrice: String(buy_num * newProduct?.preferentialPrice),
            name: `${newProduct.name + String(buy_num)} 份`,
            orgId: orgId!,
            tel: "15228626246",
            orderCode: orderCode.current,
            buyTime: new Date().toISOString()
          }).then((res) => {
            if (res.code) {
              Toast.clear();
              nav({
                pathname: `/${routeItmeType.ORDER}`,
                search: `orgId=${newProduct.orgId}&buyNum=${buy_num}&price=${
                  buy_num * newProduct?.preferentialPrice
                }&productId=${newProduct?.id}&productName=${
                  newProduct?.name
                }&orderCode=${orderCode.current}`
              });
            } else {
              Toast.show({
                icon: <CloseOutline />,
                content: "更新失败"
              });
            }
          });
        }
      }
      // 进入支付等待页面
      else {
        // 达到购买上线
        if (buyNumByOrder >= newProductData.limitBuyNum) {
          Toast.show({
            icon: <CloseOutline />,
            content: `该商品您已达到购买上限！`
          });
          return;
        }
        nav(
          `/${routeItmeType.PAYMENT}?data=${JSON.stringify(
            newProductData
          )}&buyNumByOrder=${buyNumByOrder}`
        );
      }
    };

    return (
      <BuyBtnStyle>
        <div className="price">
          <div className="nowPrice">
            {PRICE_ICON + String(buy_num * newProductData?.preferentialPrice)}
          </div>
          <div className="orginPrice">
            {buy_num * newProductData?.originPrice}
          </div>
        </div>
        <a className="phone" href="tel:15228626246">
          <PhoneFill />
        </a>
        <div
          className={classNames("buy_btn", {
            disabled_buy_btn:
              canSell || getOrderLoading || craeteLoading || !bindTel
          })}
          onClick={buyBtnClick}
        >
          {canSell ? "已售完" : isPayment ? "提交订单" : "立即抢购"}
        </div>
      </BuyBtnStyle>
    );
  }
);

export default BuyBtn;
